package com.qf.service.impl;

import com.qf.entity.User;
import com.qf.mapper.UserMapper;
import com.qf.service.ProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Description TODO
 * @Author 刘珈玮
 * @Date 2020/7/25 19:30
 */
@Service
public class ProfileServiceImpl implements ProfileService {
    @Autowired
    private UserMapper userMapper;
    /** 头像保存路径 */
    public static final String WINDOWS_PROFILES_PATH = "E:\\testImg";
    public static final String LINUX_PROFILES_PATH = "/root/img/";

    /**
     * 上传头像
     * @param newProfile 请求上传的文件
     * @param id 用户id
     * @return 返回布尔类型成功或者失败的信息
     */
    @Override
    public boolean updUserProfile(MultipartFile newProfile, Integer id) {
        // 根据Windows和Linux配置不同的头像保存路径
        String OSName = System.getProperty("os.name");
        String profilesPath = LINUX_PROFILES_PATH;
        profilesPath.replace("\\\\","/");

        if (!newProfile.isEmpty()) {
            // 当前用户
            User currentUser = userMapper.selectByPrimaryKey(id);
            String profilePathAndNameDB = currentUser.getUserImg();
            // 默认以原来的头像名称为新头像的名称，这样可以直接替换掉文件夹中对应的旧头像
            String newProfileName = profilePathAndNameDB;
            // 若头像名称不存在
            if (profilePathAndNameDB == null || "".equals(profilePathAndNameDB)) {
                newProfileName = profilesPath+ System.currentTimeMillis()+ newProfile.getOriginalFilename();
                // 路径存库
                currentUser.setUserImg(newProfileName);
                userMapper.updateByPrimaryKey(currentUser);
            }
            // 磁盘保存
            BufferedOutputStream out = null;
            try {
                File folder = new File(profilesPath);
                if (!folder.exists())
                    folder.mkdirs();
                newProfileName.replace("\\\\","/");
                FileOutputStream fileOutputStream = new FileOutputStream(newProfileName);
                out = new BufferedOutputStream(fileOutputStream);
                // 写入新文件
                out.write(newProfile.getBytes());
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        } else {
            return false;
        }
    }
}
